/*
@authors - Siddharth Sathyam, Pat LaMontagna, Alan Ruvalcaba
@Description - Chat Window GUI Code
**/

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include "im_window.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    errorMessageDialog = new QErrorMessage(this);

    ui->setupUi(this);
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_aboutButton_clicked()
{
    QMessageBox *about = new QMessageBox(0);
    about->setWindowTitle("About");
    about->setInformativeText("IM client written in Qt by \n Alan Ruvalcaba \n Siddharth Sathyam \n Patrick LaMontanga");
    about->exec();
}

void MainWindow::on_usernameEdit_textEdited(const QString &arg1)
{
    if(!arg1.isEmpty() && !arg1.isNull())
    {
	username = arg1;
    }
}

void MainWindow::on_loginButton_clicked()
{
    // Set the socket by calling the new Client method
    socket = new QTcpSocket();
    connect(socket, SIGNAL(connected()), this, SLOT(sendUserInfo()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));

    socket->connectToHost(QHostAddress::LocalHost, 1234);
    // If the Client starts...
    if(!socket->waitForConnected(3000))
    {
	errorMessageDialog->showMessage(socket->errorString());
    }
    // Temporary, have to wait until server says there's no identical usernames before showing the chat window
    else
    {
	showChatWindow();
    }
}

// Send username to the server
void MainWindow::sendUserInfo()
{
    QByteArray datablock;
    QDataStream sendStream(&datablock , QIODevice::WriteOnly);
    sendStream.setVersion(QDataStream::Qt_4_0);

    // message header 0 is intrepeted by the server as a packet containing the username of the client
    sendStream << quint16(0) << (QString) username;
    socket->write(datablock);
}

// @TODO Here to recieve a message back from server indicating that the username already exists
void MainWindow::readyRead()
{

}

void MainWindow::showChatWindow()
{
    chatWindow = new im_window();
    chatWindow->setUserName(username);
    chatWindow->setSocket(socket);
    this->close(); // Close the Login window
    chatWindow->show(); // Open the IM Windw
}
